<template>
  <el-dialog v-model="addDialog" title="公告添加" width="800" height="800">
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" class="demo-ruleForm" style="height: 400px">
      <el-form-item label="公告标题" label-width="120" prop="announcementTitle">
        <el-input autocomplete="off" v-model="formData.announcementTitle" />
      </el-form-item>
      <el-form-item label="公告内容" label-width="120" prop="announcementContent">
        <div ref="editorDiv" style="width: 600px;;height: 200px">
          <Toolbar :editor="editorRef" :mode="mode"/>
          <Editor v-model="formData.announcementContent" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated"/>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button @click="saveForm" type="primary">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount, shallowRef } from 'vue';
import axios from '@/axios/index.js';
import { ElMessage } from "element-plus";
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

const mode = ref('default');
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    // 这里如果要模拟异步获取内容，可以设置 formData.announcementContent 的值
  }, 1500);
});
// const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' };
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor === null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor;
};

let addDialog = defineModel('addDialog');
const emit = defineEmits(['loadData']);

// 表单数据
const formData = reactive({
  announcementId: '',
  announcementTitle: '',
  announcementContent: '',
});
// 表单规则
const rules = reactive({
  announcementTitle: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, message: '公告标题不低于2位', trigger: 'blur' },
    { max: 50, message: '公告标题不超过50位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && value.includes(' ')) {
          callback(new Error('公告标题不能有空格'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  announcementContent: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '<p><br></p>') {
          callback(new Error('公告内容不能为空!'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
});

// 表单引用
const ruleFormRef = ref();

// 关闭对话框
const closeDialog = () => {
  formData.announcementTitle = '';
  formData.announcementContent = '';
  addDialog.value = false;
};
// 重置表单
const resetForm = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
};
// 保存表单
const saveForm = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      axios.post("/announcement/insert", formData).then((resp) => {
        ElMessage({
          message: resp.data.message,
          type: "success",
          duration: 1500,
          onClose: () => {
            closeDialog();
            emit('loadData'); // 触发 loadData 事件通知父组件重新加载数据
          },
        });
      });
    } else {
      ElMessage.error("请检查表单填写是否正确");
    }
  });
};
</script>

<style scoped>
.editorDiv {
  min-height: 300px;
}
</style>